package com.heima.kafka.sample;

import org.apache.kafka.clients.producer.*;
import org.apache.kafka.common.serialization.StringSerializer;

import java.util.Properties;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

/**
 * @author brianxia
 * @version 1.0
 * @date 2022-09-18 14:30
 */
public class KafkaProducerQuickStart106 {

    public static void main(String[] args) {

        //1.添加kafka配置对象
        Properties properties = new Properties();
        properties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG,"192.168.200.130:9092");
        //指定key序列化器使用字符串序列化器
        properties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
        properties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());

        //2.创建生产者对象
        KafkaProducer<String, String> producer = new KafkaProducer<>(properties);

        //3.创建消息对象
        for (int i = 0; i < 10; i++) {
            ProducerRecord<String, String> producerRecord = new ProducerRecord<String, String>("itheima-003","test" + i);

            //4.发送消息
//            Future<RecordMetadata> send = producer.send(producerRecord);
//
//            try {
//                RecordMetadata recordMetadata = send.get();
//                System.out.println(recordMetadata.partition());
//                System.out.println(recordMetadata.offset());
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            } catch (ExecutionException e) {
//                e.printStackTrace();
//            }
            System.out.println(Thread.currentThread().getName());

            producer.send(producerRecord, (metadata, exception) -> {
                System.out.println(Thread.currentThread().getName());
                //会在成功发送/失败发送 消息之后，回调你这段代码
//                System.out.println(metadata.partition());
//                System.out.println(exception);
            });

        }


        //5.回收连接
        producer.close();
    }
}
